package com.miniapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Producer;
import com.miniapp.entity.MiniAttachmentEntity;
import com.miniapp.entity.MiniCaptchaEntity;
import com.miniapp.exception.RRException;
import com.miniapp.mapper.MiniAttachmentMapper;
import com.miniapp.mapper.MiniCaptchaMapper;
import com.miniapp.service.MiniAttachmentService;
import com.miniapp.service.MiniCaptchaService;
import com.miniapp.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;


/**
 * 系统用户
 * 
 * @author linyuchi
 * @date 2018/03/18
 */
@Service
public class MiniCaptchaServiceImpl extends BaseServiceImpl<MiniCaptchaMapper,MiniCaptchaEntity>  implements MiniCaptchaService {
    @Autowired
    private Producer producer;

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if(StringUtils.isBlank(uuid)){
            throw new RRException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

        MiniCaptchaEntity captchaEntity = new MiniCaptchaEntity();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //5分钟后过期
        captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
        baseMapper.insert(captchaEntity);


        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String code) {
        MiniCaptchaEntity captchaEntity = baseMapper.selectOne(new QueryWrapper<MiniCaptchaEntity>().eq("uuid",uuid));
        if(captchaEntity == null){
            return false;
        }

        //删除验证码
        baseMapper.deleteById(captchaEntity.getId());
        if(captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){
            return true;
        }
        return false;
    }
}
